 
//index.js
//获取应用实例
import api from '../../request/api.js'
import {formatDate} from '../../utils/util.js'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp()
 
Page({
  data: {
		year: 0,
		month: 0,
		date: ['日', '一', '二', '三', '四', '五', '六'],
		dateArr: [],
		isToday: 0,
		isTodayWeek: false,
    todayIndex: 0,
    nowDay: 0, //现在几号
    nowMonth: '', //现在月份
    allStaff:[], //其他员工
    show: false, 
    value: '',
    copyAllStaff: [], //备份员工做搜索功能
    replaceStaffId: '', //被请求员工id
    staff_name: '', //选中员工名字
    leaveStart: '', //开始时间
    leaveEnd: '', //请假结束时间
    dateShow: false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    status:1,
    absenceReason:'' //请假原因
	},
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  showDate(e){
    let status = e.currentTarget.dataset.status
    this.setData({
      dateShow: true,
      status: status
    })
  },
  onLoad: function () {
		let now = new Date();
		let year = now.getFullYear();
		let month = now.getMonth() + 1;
		this.dateInit();
		this.setData({
			year: year,
			month: month,
      nowMonth: month,
      isToday: '' + year + month + now.getDate(),
      nowDay: now.getDate()
		})
    this.getAllStaff()
  },
  dateInit: function(setYear,setMonth){
		//全部时间的月份都是按0~11基准，显示月份才+1
		let dateArr = [];						//需要遍历的日历数组数据
		let arrLen = 0;							//dateArr的数组长度
		let now = setYear ? new Date(setYear,setMonth) : new Date();
		let year = setYear || now.getFullYear();
		let nextYear = 0;
		let month = setMonth || now.getMonth();					//没有+1方便后面计算当月总天数
		let nextMonth = (month + 1) > 11 ? 1 : (month + 1);		
		let startWeek = new Date( year+','+(month + 1)+','+1).getDay();							//目标月1号对应的星期
		let dayNums = new Date(year,nextMonth,0).getDate();				//获取目标月有多少天
		let obj = {};		
		let num = 0;
		
		if(month + 1 > 11){
			nextYear = year + 1;
			dayNums = new Date(nextYear,nextMonth,0).getDate();
		}
		arrLen = startWeek + dayNums;
		for(let i = 0; i < arrLen; i++){
			if(i >= startWeek){
				num = i - startWeek + 1;
				obj = {
					isToday: '' + year + (month + 1) + num,
					dateNum: num,
				  weight: 5,
          month : month <= 10 ? '0'+month : month,
          year : year
				}
			}else{
				obj = {};
			}
			dateArr[i] = obj;
		}
		this.setData({
			dateArr: dateArr
		})
  
		let nowDate = new Date();
		let nowYear = nowDate.getFullYear();
		let nowMonth = nowDate.getMonth() + 1;
		let nowWeek = nowDate.getDay();
		let getYear = setYear || nowYear;
		let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
 
		if (nowYear == getYear && nowMonth == getMonth){
			this.setData({
				isTodayWeek: true,
				todayIndex: nowWeek
			})
		}else{
			this.setData({
				isTodayWeek: false,
				todayIndex: -1
			})
		}
	},
	lastMonth: function(){
		//全部时间的月份都是按0~11基准，显示月份才+1
		let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
		let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
		this.setData({
			year: year,
			month: (month + 1)
		})
		this.dateInit(year,month);
	},
	nextMonth: function(){
		//全部时间的月份都是按0~11基准，显示月份才+1
		let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
		let month = this.data.month > 11 ? 0 : this.data.month;
		this.setData({
			year: year,
			month: (month + 1)
		})
		this.dateInit(year, month);
  },
  checkDate(event){
    this.setData({
      nowDay: event.currentTarget.dataset.index
    })
    
  },
  changeHandle(e) {
    this.setData({
      absenceReason: e.detail
    })
  },
  postLeave() {
    const {absenceReason} = this.data

    api('POST', '', {
      absenceStaffId,
      replaceStaffId,
      beginTime,
      endTime,
      absenceReason
    })
  },
  async getAllStaff(){
    const {data: res} = await api('GET', 'Recycle/staff/getOtherStaff',{
      staff_id: wx.getStorageSync('userInfo').user_id
    })
    if(res.code===200){
      this.setData({
        allStaff: res.data,
        copyAllStaff: res.data
      })
    }
  },
  searchArea(e) {
    const value = e.detail
    const { copyAllStaff } = this.data
    let res = copyAllStaff.filter(i => {
      return i.staff_name.includes(value)
    })
    this.setData({
      allStaff: res
    })
  },
  //关闭面板
  onClose() {
    this.setData({
      show: false
    })
  },
  showStaff() {
    this.setData({
      show: true
    })
  },
  chooseArea(e) {
    let id = e.currentTarget.dataset.id
    this.data.allStaff.forEach(i => {
      if (id == i.staff_id) {
        this.setData({
          staff_name: i.staff_name,
          show: false,
          replaceStaffId: id
        })
      }
    })
  },
  confirmDate(e){

    let { currentDate, status, leaveStart, leaveEnd} = this.data
    let a = formatDate(currentDate)
    if(status==1){
      console.error(new Date(leaveStart));
      console.error(new Date(leaveEnd));
      if(leaveEnd != '' && new Date(leaveStart) < new Date(leaveEnd)){
        Toast('结束时间必须大于开始时间');return;
      }
      this.setData({
        leaveStart: formatDate(currentDate),
        dateShow: false
      })
    }else{
      if(leaveStart == ''){
        Toast('请先选择开始时间');return;
      }
      if (leaveStart <= formatDate(currentDate)){
        this.setData({
          leaveEnd: formatDate(currentDate),
          dateShow: false
        })
      }else{
        Toast('结束时间必须大于开始时间');return;
      }
    }
  },
  closeHandle(){
    this.setData({
      dateShow: false
    })
  },
  async postleaves(){
    const { leaveStart, leaveEnd, absenceReason, replaceStaffId} = this.data
    if (!leaveStart && !leaveEnd){
      Toast('请完善请假时间')
      return;
    }
    if (!replaceStaffId){
      Toast('请选择员工')
      return;
    }
    if(leaveEnd < leaveStart){
      Toast('结束时间必须大于开始时间');
      return;
    }
    const {data: res} = await api('POST', 'Recycle/staff/addAbsence',{
      absenceStaffId: wx.getStorageSync('userInfo').user_id,
      replaceStaffId,
      beginTime: leaveStart,
      endTime:leaveEnd,
      absenceReason : absenceReason
    })
    if(res.code ===200){
      Toast(res.msg)
      setTimeout(function () {
        wx.navigateTo({
          url: '../leaveReview/index',
        })
       }, 1000) //延迟时间 这里是1秒
    }else{
      Toast(res.msg)
    }
  }
})
